package com.StarStudio.Controller;


import com.StarStudio.Service.*;
import com.StarStudio.Utils.HttpRequestUtils;
import com.StarStudio.Utils.QueryPageUtils;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/exchange")
@Api(tags = "兑换记录接口")
public class ExchangeController {

    @Autowired
    private ExchangeService exchangeService;

    @Autowired
    CouponsService couponsService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    private AuthService authenticate;

    @Autowired
    OrderService orderService;

    private static final Logger log = LoggerFactory.getLogger(ExchangeController.class);

    /**
     * 条件查询 兑换记录分页接口
     * @param exchange 兑换记录对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    @ResponseBody
    @ApiOperation("兑换记录分页接口 -> 支持条件检索，检索条件封装在兑换记录对象Exchange中。如需分页，必传pageNum和pageSize")
    public PageResult page(Exchange exchange){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Exchange> exchangeList;
        long allRecordNumber;
        try {
            exchangeList = exchangeService.findExchangeList(exchange);
            allRecordNumber = exchangeService.findAllRecordNumber();
            pageInfo = new PageInfo<>(exchangeList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), exchangeList, allRecordNumber);
    }

    /**
     * 导出兑换记录到 Excel表格
     * @param response http响应
     * @param exchange 兑换记录对象
     */
    @Log(title = "兑换记录管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    @ApiOperation("兑换记录Excel导出接口 -> 支持条件检索，检索条件封装在兑换记录对象Exchange中")
    public void export(HttpServletResponse response, Exchange exchange) {
        List<Exchange> list = exchangeService.findExchangeList(exchange);
        ExcelUtil<Exchange> util = new ExcelUtil<>(Exchange.class);
        util.exportExcel(response, list, "优惠券兑换数据");
    }

    /**
     * 根据兑换记录ID查找兑换记录
     * @param id 兑换记录ID
     * @return 结果对象 Result
     */
    @GetMapping("/{id}")
    @ResponseBody
    @ApiOperation("根据兑换记录ID查找兑换记录接口 -> path必传兑换记录ID")
    public Result findExchangeById(@PathVariable Long id){
        if (id == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        Exchange byExchangeId;
        try {
            byExchangeId = exchangeService.findByExchange_id(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_EXCHANGE_SUCCESS,byExchangeId);
    }

    /**
     * 根据用户ID查找兑换记录
     * @param id 用户ID
     * @return 结果对象 Result
     */
    @GetMapping("/byUserId/{id}")
    @ResponseBody
    @ApiOperation("根据用户ID查找兑换记录接口 -> path必传用户ID")
    public Result findExchangeByUserId(@PathVariable Long id){
        if (id == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        List<Exchange> byExchange_user_id = exchangeService.findByExchange_user_id(id);
        List<ExchangeResult> exchangeResultList = new ArrayList<>();
        try {
            if (byExchange_user_id.size() > 0){
                for (Exchange exchange : byExchange_user_id) {
                    ExchangeResult exchangeResult = new ExchangeResult();
                    if (exchange.getGoods_item_id() != null && exchange.getGoods_item_id() > 0){ /* 实体商品兑换记录 */
                        Goods byGoods_item_id = goodsService.findByGoods_Item_Id(exchange.getGoods_item_id());
                        exchangeResult.setExchange(exchange);
                        exchangeResult.setGoods(byGoods_item_id);
                    }else if (exchange.getCoupons_item_id() != null && exchange.getCoupons_item_id() > 0){ /* 优惠券兑换记录 */
                        Coupons byCoupons_item_id = couponsService.findByCoupons_item_id(exchange.getCoupons_item_id());
                        exchangeResult.setExchange(exchange);
                        exchangeResult.setCoupons(byCoupons_item_id);
                    }
                    //订单的收货地址和收货电话
                    Map<String,Object> param = new HashMap<>();
                    Orders order = orderService.findByOrderId(exchange.getOrder_id());
                    if (order != null){
                        param.put("orderTime",order.getOrder_time());
                    }
                    exchange.setParams(param);
                    exchangeResultList.add(exchangeResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_EXCHANGE_SUCCESS, exchangeResultList);
    }

    /**
     * 根据兑换记录ID删除兑换记录（可单个删除也可批量删除）
     * @param Ids 待删除的兑换记录ID
     * @return 结果对象 Result
     */
    @Log(title = "兑换记录管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    @ResponseBody
    @ApiOperation("根据兑换记录ID删除兑换记录接口 -> 可单个删除也可批量删除，path传兑换记录ID数组")
    public Result deleteExchange(@PathVariable Long[] Ids){
        if (Ids == null || Ids.length == 0){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            if (Ids.length > 1){
                for (Long id : Ids) {
                    exchangeService.deleteExchangeById(id);
                }
            }else {
                exchangeService.deleteExchangeById(Ids[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_EXCHANGE_SUCCESS);
    }

    /**
     * 新增兑换记录
     * @param exchange 兑换记录
     * @return 结果对象 Result
     */
    @Log(title = "兑换记录管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    @ApiOperation("兑换记录新增接口 -> 对应的订单ID、对应的用户ID、商家ID不能为空")
    public Result addExchange(@RequestBody Exchange exchange){
        if (exchange.getOrder_id() == null || exchange.getExchange_user_id() == null || exchange.getStore_id() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            exchangeService.addExchange(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_EXCHANGE_SUCCESS);
    }

    /**
     * 修改兑换记录
     * @param exchange 兑换记录
     * @return 结果对象 Result
     */
    @Log(title = "兑换记录管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    @ApiOperation("兑换记录修改接口 -> 兑换记录ID、对应的订单ID、对应的用户ID不能为空")
    public Result updateExchange(@RequestBody Exchange exchange){
        if (exchange == null || exchange.getExchange_id() == null || exchange.getOrder_id() == null || exchange.getExchange_user_id() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            if (exchange.getExchange_status().equals("已使用")) {
                exchange.setUse_time(new Timestamp(new Date().getTime()));
            }
            exchangeService.updateExchange(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_EXCHANGE_SUCCESS);
    }

    /**
     * 核销码访问接口  改变兑换记录状态  跳转不同状态的提示页面
     * @param coupons_item_id 优惠券个体ID
     * @return 结果对象 Result
     */
    @Log(title = "优惠券现场核销", businessType = BusinessType.UPDATE)
    @GetMapping("/check/{coupons_item_id}")
    @ApiOperation("核销码访问接口 -> 改变兑换记录状态，跳转不同状态的提示页面，这里首先跳转商家登录页面，path必传优惠券个体ID")
    public String checkSellCode(@PathVariable long coupons_item_id, HttpServletRequest request){
        request.setAttribute("coupons_item_id",coupons_item_id);
        return "login";  //跳转商家登录页面
    }

    /**
     * 验证商家身份  若通过则执行核销操作，更改优惠券使用状态
     * @param login 登录实体类
     * @param coupons_item_id 优惠券ID
     * @param request HttpServletRequest对象
     * @return 相应的页面
     */
    @PostMapping("/login/{coupons_item_id}")
    @ApiOperation("核销时商家登录接口 -> 验证商家身份，若通过则执行核销操作，更改优惠券使用状态。path必传优惠券个体ID")
    public String ExchangeLogin(Login login,@PathVariable long coupons_item_id,HttpServletRequest request){
        // 用户验证
        CheckUser loginUser;
        try {
            String s = JSONObject.toJSONString(authenticate.checkUser(login).getObject());
            loginUser = JSONObject.parseObject(s,CheckUser.class);
            if (loginUser == null){
                request.setAttribute("errMsg",MessageConstant.STORE_NOT_EXIST);
                return "login";
            }
        } catch (Exception e) {
            request.setAttribute("errMsg",MessageConstant.STORE_NOT_EXIST);
            return "login";
        }
        Coupons byCoupons_item_id = null;
        Exchange byExchange_id;
        try {
            //判断当前优惠券的兑换状态
            byCoupons_item_id = couponsService.findByCoupons_item_id(coupons_item_id);
            byExchange_id = exchangeService.findByCoupons_item_id(coupons_item_id);
            if (byExchange_id != null){
                if (byExchange_id.getExchange_status().equals(MessageConstant.EXCHANGE_STATUS_EXCHANGED_BUT_NOT_USED) && !byCoupons_item_id.getPlace_of_use().equals("全部商家")
                        && !byCoupons_item_id.getPlace_of_use().equals(loginUser.getNickName())) {
                    request.setAttribute("login_store",loginUser.getNickName());
                    request.setAttribute("aim_store",byCoupons_item_id.getPlace_of_use());
                    request.setAttribute("couponName",byCoupons_item_id.getCoupon_name());
                    request.setAttribute("checkCode",coupons_item_id);
                    request.setAttribute("errorMsg",MessageConstant.STORE_NOT_MATCH);
                    return "error1";
                }
                if (byExchange_id.getExchange_status().equals(MessageConstant.EXCHANGE_STATUS_EXCHANGED_BUT_NOT_USED)){
                    exchangeService.updateExchangeStatus(coupons_item_id,MessageConstant.EXCHANGE_STATUS_USED, loginUser.getNickName());
                }else if (byExchange_id.getExchange_status().equals(MessageConstant.EXCHANGE_STATUS_EXPIRED)){
                    request.setAttribute("couponName","很抱歉，该" + byCoupons_item_id.getCoupon_name());
                    request.setAttribute("expiredMsg",MessageConstant.EXCHANGE_STATUS_EXPIRED + "！");
                    request.setAttribute("login_store",loginUser.getNickName());
                    request.setAttribute("checkCode",coupons_item_id);
                    request.setAttribute("expiredTime","过期时间：" + byCoupons_item_id.getDate_use_end());
                    return "expired";
                } else {
                    request.setAttribute("couponName","该" + byCoupons_item_id.getCoupon_name());
                    request.setAttribute("login_store",loginUser.getNickName());
                    request.setAttribute("usedMsg",MessageConstant.COUPON_ALREADY_EXCHANGED);
                    request.setAttribute("exchange_store",byExchange_id.getExchange_store());
                    request.setAttribute("checkCode",coupons_item_id);
                    request.setAttribute("useTime","使用时间：" + byExchange_id.getUse_time());
                    return "used";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (byCoupons_item_id != null) {
                request.setAttribute("couponName",byCoupons_item_id.getCoupon_name());
            }
            request.setAttribute("checkCode",coupons_item_id);
            request.setAttribute("login_store",loginUser.getNickName());
            request.setAttribute("errorMsg",MessageConstant.SERVER_ERROR);
            return "error";
        }
        if (byExchange_id == null){
            request.setAttribute("errMsg",MessageConstant.COUPON_NOT_EXIST);
            return "error";
        }
        Exchange byCoupons_item_id1 = exchangeService.findByCoupons_item_id(coupons_item_id);
        request.setAttribute("couponName",byCoupons_item_id.getCoupon_name());
        request.setAttribute("login_store",loginUser.getNickName());
        request.setAttribute("successMsg",MessageConstant.UPDATE_EXCHANGE_STATUS_SUCCESS);
        request.setAttribute("exchange_store",byCoupons_item_id1.getExchange_store());
        request.setAttribute("checkCode",coupons_item_id);
        request.setAttribute("useTime","使用时间：" + new Timestamp(new Date().getTime()));
        return "success";
    }

    @PostMapping("/test")
    @ResponseBody
    public Result test(@RequestBody Login login){
        Result result;
        try {
             result = authenticate.checkUser(login);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,e.getMessage());
        }
        return result;
    }

    @PostMapping("/token")
    @ResponseBody
    public Result test1(@RequestBody Login login){
        return authenticate.getToken(login);
    }

    /**
     * 优惠券使用状态更改
     * @param couponsItemId 优惠券ID
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/05/11
     */
    @Log(title = "优惠券使用状态更改", businessType = BusinessType.UPDATE)
    @PostMapping("/couponStatus/{couponsItemId}")
    @ResponseBody
    @ApiOperation("优惠券使用状态更改接口 -> 将优惠券使用状态更改为已使用，path必传优惠券个体ID和立减金链接")
    public Result updateUsedStatus(@PathVariable Long couponsItemId,String link){
        if (couponsItemId == null || StringUtils.isBlank(link)){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            exchangeService.updateExchangeStatusAndLink(couponsItemId,"已使用","中国工商银行",link);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_EXCHANGE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_EXCHANGE_SUCCESS);
    }

    /**
     * 获取微信立减金链接接口
     * @param vlinkdata AES加密后的JSON字符串
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/05/13
     */
    @ApiOperation("发送请求获取微信立减金链接接口 -> 加密字符串不能为空")
    @PostMapping("/getLink")
    @ResponseBody
    public Result sendRequest(String vlinkdata){
        if (StringUtils.isBlank(vlinkdata)){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        String res;
        try {
            String url = "https://didao.lovemojito.com/icbcMiNi/collection/placeOutOrder.php";
            HashMap<String, String> param = new HashMap<>();
            param.put("vlinkdata",vlinkdata);
            res = HttpRequestUtils.postWithParamsForString(url, param);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_LINK_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_LINK_SUCCESS,res);
    }
}
